package flante;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Title: Flante EventListActivity</p>
 * <p>Description: This class fetches and displays a listView of events from server</p>
 * @author Aaron Cook, Mike Haas, Kyle Kolstad
 * @email aaron.cook@my.uwrf.edu, michael.haas.@my.uwrf.edu, kyle.kolstad@my.uwrf.edu
 * @date 12/4/2013
 */
public class EventListActivity extends ListActivity {
    /**
     * EventListActivity Data Members
     */
    private List<Event> eventList = new ArrayList<Event>();
    private EventListAdapter eventListAdapter = null;

    /**
     * Activity creates a simple listView
     * When clicked, show a toast with the TextView text
     * @param savedInstanceState
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_list);
        ListView listView = (ListView) findViewById(android.R.id.list);

        eventListAdapter = new EventListAdapter(eventList, this);
        listView.setAdapter(eventListAdapter);

        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Toast.makeText(getApplicationContext(),
                        ((TextView) view).getText(), Toast.LENGTH_LONG).show();
            }
        });

        FetchEventsAsync fetchEventsAsync = new FetchEventsAsync();
        fetchEventsAsync.execute("http://10.0.2.2:9000/events");

    }

    /**
     * Creates a httpClient, sets HttpGet to the url. Sets the httpGet
     * header to accept json, then the httpclient executes the getHttp
     * and stores the response. Then the content of the response gets
     * stored into an inputStream  if the inputStream !=null
     * then the inputStream gets converted into strings and
     * then the eventList will be cleared.
     * then the Strings parsed into a JSONArray which we loop through getting the
     * description and creating a new event object and stores it back into
     * the eventList.
     * @param url
     * @param events
     * @return result
     * @see org.apache.http.HttpResponse;
     * @see
     */
    public static String GET(String url, List<Event> events){
        InputStream inputStream = null;
        String result = "";
        String event = "";

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);

            httpGet.setHeader("Accept", "application/json");

            HttpResponse httpResponse = httpclient.execute(httpGet);
            inputStream = httpResponse.getEntity().getContent();


            if(inputStream != null){
                events.clear();
                result = convertInputStreamToString(inputStream);
                JSONArray arr = new JSONArray(result);
                for(int i=0;i<arr.length();i++){
                  event = arr.getJSONObject(i).getString("description");

                    events.add(new Event().setDescription(event));
                }

            }
                else{
                result = "Did not work!";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
    /**
     *<p>Title: Flante FetchEventsAsync</p>
     * <p>Description: This class creates a thread to run in the background.</p>
     * @author Aaron Cook, Mike Haas, Kyle Kolstad
     * @email aaron.cook@my.uwrf.edu, michael.haas.@my.uwrf.edu, kyle.kolstad@my.uwrf.edu
     * @date 12/4/2013
     */
    private class FetchEventsAsync extends AsyncTask<String, Void, String> {
        /**
         * creates a new AsyncTask Thread that calls the
         * GET(String url, List<Event> events) and runs in the background.
         *@see android.os.AsyncTask#doInBackground(Object[])
         *@see android.os.AsyncTask#onPostExecute(Object)
         *
         */
        @Override
        protected String doInBackground(String... params) {
//
            return GET(params[0], eventList);
        }
        /**
         *Runs on the UI thread after doInBackground(Params...).
         * and updates the eventListAdapter with the new eventList
         * @see android.os.AsyncTask#onPostExecute(Object)
         */
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            eventListAdapter.notifyDataSetChanged();
        }
    }

    /**
     *Converts the inputSteam into a String result
     * @param inputStream
     * @return result
     * @throws java.io.IOException
     * @see java.io.InputStreamReader
     * @see java.io.BufferedReader
     */
    private static String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }
}
